package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"lucky_srv/es"
	"lucky_srv/models"
	"strconv"

	"lucky_srv/internal/svc"
	"lucky_srv/lucky"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddGoodsLogic {
	return &AddGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddGoodsLogic) AddGoods(in *lucky.AddGoodsRequest) (*lucky.AddGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var g models.Goods

	if in.Title == "" || in.Price == 0 || in.Stock == 0 {
		return nil, errors.New("参数不能为空")
	}

	g.Title = in.Title
	g.Taste = in.Taste
	g.Ingredient = in.Ingredient
	g.Price = float64(in.Price)
	g.Stock = in.Stock
	g.ImageUrl = in.ImageUrl
	g.Likes = in.Likes

	if err = g.CreateGoods(); err != nil {
		logx.Error("商品发布失败")
		return nil, errors.New("商品发布失败")
	}

	data, err := json.Marshal(g)
	if err != nil {
		log.Fatalf("Error marshaling document: %s", err)
	}
	//在添加商品时将信息同步进Es数据库中
	req := esapi.IndexRequest{
		Index:      "goods2",
		DocumentID: strconv.Itoa(int(g.ID)),
		Body:       bytes.NewReader(data),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), es.EsClient)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	return &lucky.AddGoodsResponse{
		Id: int64(g.ID),
	}, nil
}
